﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using umbraco;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.SlideShare
{
    public class SlideShareXsltExtension : AbstractXsltExtension
    {
        public static XPathNodeIterator GetMedia(int docTypeDefinitionId, int id)
        {
            var provider = GetProvider<SlideShareProvider>(docTypeDefinitionId);
            var service = new SlideShareService(provider.Config);

            try
            {
                var slideshow = service.GetSlideshow(id);

                var xd = new XmlDocument();
                var docNode = xmlHelper.addTextNode(xd, "Slideshow", "");

                if (slideshow != null)
                {
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Id", slideshow.Id.ToString()));
                    docNode.AppendChild(xmlHelper.addCDataNode(xd, "Title", slideshow.Title));
                    docNode.AppendChild(xmlHelper.addCDataNode(xd, "Description", slideshow.Description));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Status", slideshow.Status.ToString()));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Username", slideshow.Username));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "ThumbnailUrl", slideshow.ThumbnailUrl));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "ThumbnailSmallUrl", slideshow.ThumbnailSmallUrl));
                    docNode.AppendChild(xmlHelper.addCDataNode(xd, "EmbedCode", slideshow.EmbedCode));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Created", slideshow.Created.ToString()));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Updated", slideshow.Updated.ToString()));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Language", slideshow.Language));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Format", slideshow.Format));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Download", slideshow.Download ? "1" : "0"));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "DownloadUrl", slideshow.DownloadUrl));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Type", slideshow.Type.ToString()));
                }

                xd.AppendChild(docNode);

                return xd.CreateNavigator().Select("/Slideshow");
            }
            catch (Exception e)
            {
                return e.ToXPathNodeIterator();
            }
        }
    }
}